/**
 * Copyright (c) 2005-2009 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: JCaptchaFilter.java 382 2009-08-27 17:37:44Z calvinxiu $
 */
package com.itump.base.util.security;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
/**
 * 验证码生成
 * @author  
 *
 */
public class CaptchaFilter implements Filter {
	
	private final static int WIDTH=60;
	private final static int HEIGHT=20;

//	private static Logger logger = LoggerFactory.getLogger(CaptchaFilter.class);

	/**
	 * Filter回调初始化函数.
	 */
	public void init(final FilterConfig fConfig) throws ServletException {
	}

	/**
	 * Filter回调退出函数.
	 */
	public void destroy() {
	}

	/**
	 * Filter回调请求处理函数.
	 */
	public void doFilter(final ServletRequest theRequest, final ServletResponse theResponse, final FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) theRequest;
		HttpServletResponse response = (HttpServletResponse) theResponse;
		String servletPath = request.getServletPath();

		//符合filterProcessesUrl为验证处理请求,其余为生成验证图片请求.
		if (StringUtils.startsWith(servletPath, "/j_spring_security_check")) {
			boolean validated = validateCaptchaChallenge(request);
			if (validated) {
				chain.doFilter(request, response);
			} else {
				redirectFailureUrl(request, response);
			}
		} else {
			genernateCaptchaImage(request, response);
		}
	}

	/**
	 * 生成验证码图片.
	 */
	protected void genernateCaptchaImage(final HttpServletRequest request, final HttpServletResponse response)
			throws IOException {

        HttpSession session = request.getSession();    
        response.setContentType("image/jpeg");
        ServletOutputStream sos = response.getOutputStream();
        
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        
        BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
        Graphics g=image.getGraphics();
        
        char[] rands = generateCheckCode();
        drawBackground(g);
        drawRands(g,rands);
        g.dispose();
        
        ByteArrayOutputStream bos= new ByteArrayOutputStream();
        ImageIO.write(image,"JPEG",bos);
        byte[] buf = bos.toByteArray();
        response.setContentLength(buf.length);
        sos.write(buf);
        bos.close();
        sos.close();
        session.setAttribute("check_code", new String(rands));
	}
	 private void drawBackground(Graphics g) {
	        g.setColor(new Color(0xDCDCDC));
	        g.fillRect(0, 0, WIDTH, HEIGHT);
	        Random random = new Random();
	        for(int i=0;i<120;i++){
	            int x = random.nextInt(WIDTH);
	            int y = random.nextInt(HEIGHT);
	            int red = random.nextInt(255);
	            int green = random.nextInt(255);
	            int blue = random.nextInt(255);
	            g.setColor(new Color(red,green,blue));
	            g.drawOval(x, y, 1, 0);
	        }
	    }
	    private void drawRands(Graphics g, char[] rands){
	        g.setColor(Color.BLACK);
	        g.setFont(new Font(null,Font.ITALIC|Font.BOLD,18));
	        g.drawString(""+rands[0], 1, 17);
	        g.drawString(""+rands[1], 16, 15);
	        g.drawString(""+rands[2], 31, 18);
	        g.drawString(""+rands[3], 46, 16);
	    }
	    private char[] generateCheckCode() {
	       // String chars = "0123456789abcdeFGhIJkLmnOPQRSTuvwxyz";
	        String chars = "0123456789";
	        char[] rands = new char[4];
	        Random random = new Random();
	        for(int i=0;i<4;i++){
	            int rand = random.nextInt(10);
	            rands[i]=chars.charAt(rand);
	        }
	        return rands;
	 }
	    
	/**
	 * 验证验证码.
	 */
	protected boolean validateCaptchaChallenge(final HttpServletRequest request) {
		String checkCode = request.getParameter("j_checkcode");
		Object sessionCheckCode = request.getSession().getAttribute("check_code");
		
		if (checkCode != null && checkCode.equals(sessionCheckCode)) {
			return true;
		}
		return false;
	}

	/**
	 * 跳转到失败页面.
	 * 
	 * 可在子类进行扩展, 比如在session中放入SpringSecurity的Exception.
	 */
	protected void redirectFailureUrl(final HttpServletRequest request, final HttpServletResponse response)
			throws IOException {
		response.sendRedirect(request.getContextPath() + "user!login.action");
	}
}
